package com.ndood.admin.service.system.agent.impl;

import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ndood.admin.pojo.system.agent.AgentPermPo;
import com.ndood.admin.pojo.system.agent.dto.AgentPermDto;
import com.ndood.admin.repository.system.agent.AgentPermRepository;
import com.ndood.admin.repository.system.agent.manager.AgentPermRepositoryManager;
import com.ndood.admin.service.system.agent.SystemAgentPermService;
import com.ndood.common.base.util.JPAUtil;

/**
 * 资源模块业务类
 * @author ndood
 */
@Transactional
@Service
public class SystemAgentPermServiceImpl implements SystemAgentPermService {
	
	@Autowired
	private AgentPermRepository agemtPermDao;

	@Autowired
	private AgentPermRepositoryManager agentPermRepositoryManager;
	
	@Override
	public List<AgentPermDto> getPermList() throws Exception {
		return agentPermRepositoryManager.getPermList();
	}

	@Override
	public void batchDeletePerm(Integer[] ids) {
		for (Integer id : ids) {
			agemtPermDao.deleteById(id);
		}
	}

	@Override
	public AgentPermDto addPerm(AgentPermDto dto) throws Exception {
		// Step1: 补充相关字段
		dto.setCreateTime(new Date());
		dto.setUpdateTime(new Date());
		AgentPermPo po = new AgentPermPo();
		
		// Step2: 处理上级资源
		Integer parentId = dto.getParentId();
		if (parentId != null) {
			AgentPermPo parent = agemtPermDao.findById(parentId).get();
			po.setParent(parent);
		}

		// Step3: 保存并返回
		JPAUtil.childToFather(dto, po);
		po = agemtPermDao.save(po);
		dto.setId(po.getId());
		return dto;
	}

	@Override
	public AgentPermDto getPerm(Integer id) throws Exception {
		// Step1: 获取资源信息
		AgentPermDto dto = new AgentPermDto();
		AgentPermPo po = agemtPermDao.findById(id).get();
		JPAUtil.fatherToChild(po, dto);
		dto.setParent(po.getParent());
		return dto;
	}

	@Override
	public AgentPermDto updatePerm(AgentPermDto dto) throws Exception {
		// Step1: 更新资源信息
		dto.setUpdateTime(new Date());
		AgentPermPo po = agemtPermDao.findById(dto.getId()).get();
		JPAUtil.childToFather(dto, po);
		agemtPermDao.save(po);
		
		// Step2: 获取隐含属性用于异步回显
		JPAUtil.fatherToChild(po, dto);
		return dto;
	}
}
